package com.zym.application.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zym.application.model.ReturnModel;
import com.zym.application.session.Http;
import com.zym.application.session.HttpCall;
import com.zym.framework.model.SelectModel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * QQ 165149324
 * 臧英明
 *
 * @author
 * @create 2021-03-01
 */
public class BaseDataSetvice {
    public static BaseDataSetvice baseDataSetvice = new BaseDataSetvice();
    private BaseDataSetvice(){
    }
    public static BaseDataSetvice getInstance(){
        return baseDataSetvice;
    }
    private final JSONObject cacheMap = new JSONObject();




    public void update(String url,JSONObject par) {
        Http.post(url, par, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                cacheMap.put(url,returnModel.getObj());
            }
        });
    }
    public JSONObject getMapData(String url) {
        return getMapData(url,null);
    }
    public JSONObject getMapData(String url,JSONObject par){
        if (!cacheMap.containsKey(url) || cacheMap.getJSONObject(url).size() == 0){
            update(url,par);
        }
        return cacheMap.getJSONObject(url);
    }
    public JSONArray getArrayData(String url) {
        return getArrayData(url,null);
    }
    public JSONArray getArrayData(String url, JSONObject par){
        if (!cacheMap.containsKey(url) || cacheMap.getJSONArray(url).size() == 0){
            update(url,par);
        }
        return cacheMap.getJSONArray(url);
    }
    public static List toSelectModelList(JSONArray list,String key,String value){
        List array = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.getJSONObject(i);
            SelectModel selectModel = new SelectModel();
            Object valueObj = jsonObject.get(value);
            Object keyObj = jsonObject.get(key);

            if(keyObj instanceof BigDecimal){
                double doubleValue = jsonObject.getDoubleValue(key);
                selectModel.setId(String.valueOf(doubleValue) );
            }else {
                selectModel.setId(jsonObject.getString(key));
            }
            if(valueObj instanceof BigDecimal){
                double doubleValue = jsonObject.getDoubleValue(value);
                selectModel.setValue(String.valueOf(doubleValue) );
            }else {
                selectModel.setValue(jsonObject.getString(value));
            }

            array.add(selectModel);
        }
        return array;
    }
}
